<!DOCTYPE html>
<html>
<head>
    <title>$q Demo</title>
    <link type="text/css" rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
    <script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
    <script type="text/javascript" src="/bower_components/angularjs/angular.js"></script>
    <script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <style type="text/css">

    </style>
</head>
<body ng-app="app">
<div class="container" ng-controller="Demo6Ctrl">
    <input type="text" ng-model="num"> <button ng-click="test()">计算</button>
</div>
<script>
    angular.module('app', [])
            .factory('syncPromise', ['$q', function ($q) {
                return function (num) {
                    var deferred = $q.defer();

                    setTimeout(function(){
                        if (num % 2 == 0) {
                            deferred.resolve(num+"%"+2 + '=' + num%2);
                        }else{
                            deferred.reject("不是偶数");
                        }
                    },3000);
                    return deferred.promise;
                }
            }])
            .controller('Demo6Ctrl', ['$scope','syncPromise', function ($scope, syncPromise) {

               $scope.test = function () {
                   alert($scope.num);
                   var p = syncPromise($scope.num);
                   p.then(function (result) {
                       alert("success: " + result);
                   },function(reason){
                       alert("faild:" + reason);
                   });
               }
            }]);
</script>
</body>
</html>